<?php
require_once 'includes/image_resizer.php'; 
require_once 'includes/functions.php'; 
require_once 'includes/class.phpmailer.php';
//print_r($_REQUEST);
$smsg="";
if($_SESSION['user_id_sess']=="") {
	echo "<script type='text/javascript'> window.location='index.php?signin&url=refer'; </script>";
}
@extract($_REQUEST);
if(isset($_REQUEST['post_email_address']))
{

	$sqlSelItemUser="select * from tbl_users where user_id='".$_SESSION['user_id_sess']."'";
	$rstSelItemUser=mysql_query($sqlSelItemUser);
	$rowSelItemUser=mysql_fetch_array($rstSelItemUser);
	//$today=date("Y-m-d G:i:s",time());
	$user_name1=$rowSelItemUser['first_name'].' '.$rowSelItemUser['last_name'];
	
	$email_addresses=$_REQUEST['post_email_address'];	
	
	if(isset($_POST['submitbutton']))
	{
		$varEmailAddress=$_POST['post_email_address'];
		$varEmailArray=array();
		$varEmailArray=explode("\n",$varEmailAddress);
		$count=count($varEmailArray);
		$strMessage="";
		for($i=0;$i<$count;$i++)
		{	
			$strEmail = $varEmailArray[$i];
			//$sqlPost="select * from tbl_referer where ref_email='".$strEmail."'";
			//$rstPost=mysql_fetch_array($sqlPost) or die(mysql_error());
			
			$sqlSelItem_User="select * from tbl_users where email='".$strEmail."'";
			$rstSelItem_User=mysql_query($sqlSelItem_User);
			$rowSelItem_User=mysql_fetch_array($rstSelItem_User);
			
			if(!is_array($rowSelItem_User))
			{
						
				$sqlSelItem="select * from tbl_referer where ref_email='".$strEmail."'";
				$rstSelItem=mysql_query($sqlSelItem);
				$rowSelItem=mysql_fetch_array($rstSelItem);
			
				if(!is_array($rowSelItem))
				{
					$sqlPost="insert tbl_referer(ref_email,refer_by_user_id,refer_by_user_type_id,refer_to_user_id,isActive) values('".$strEmail."','".$_SESSION['user_id_sess']."','".$_SESSION['user_type_sess']."',0,'0')";
					$rstPost=mysql_query($sqlPost) or die(mysql_error());
					$strMessage .="This email id has been refered successfully : ".$strEmail."<br/>";	
					
					$msg="<table width='100%' border='0' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px; line-height:25px'>
					  <tr>
						<td width='18%' height='41'><table width='100%' border='0'>
						  <tr>
							<td width='19%' height='68'><img src='http://genisofttechnologies.com/php1/swapen/images/logo.gif' width='208' height='83'></td>
							<td width='81%'>Swapen sent this message from Referal System.</td>
						  </tr>
						</table></td>
					  </tr>
					  <tr>
						<td height='32' colspan='2' style='font-family:Verdana, Arial, Helvetica, sans-serif;font-size:13px;color:#FFFFFF;background-color:#0FB6FA;'><b>&nbsp;&nbsp;Complete your Swapen registration</b></td>
					  </tr>
					  <tr>
						<td>
						  <table width='100%' border='0'>
							<tr>
							  <td width='71%' height='124'><p><b>Hi </b>, </p>
							  <p>Your friend wants to make sure that you are not missing out on a revolutionary marketplace called swapen.com.  Swapen.com offers you more than any other website. You can sell your products or have your products sold for you, refer people you know and get paid every time they complete any transaction, have people find items for you at your choice price, and many more. Swapen.com gives you all of the tools to buy, sell, and make money, best of all its free! How you ask? Get all of your answers at swapen.com. We also have premium accounts for Merchants or Wholesalers. Visit swapen.com and see why we are so much revolutionary. </p></td>
							  <td width='29%' style='text-align:center'><b>Sign up Today!</b><a href='http://swapen.com/index.php?signup' target='_blank' style='text-decoration:none; color:#FFFFFF'><img src='http://swapen.com/images/register_now.gif' width='138' height='43'></a></td>
							</tr>
						  </table>
						</td>
					  </tr>
					  <tr>
						<td><table width='100%' border='0'>
						  <tr>
							<td height='28' style='background-color:#F3F3F3'><b>If the above link does not work:</b></td>
						  </tr>
						  <tr>
							<td height='80'>Type in or copy and paste this link into your Web browser: <br>
							  <a href='swapen.com/index.php' target='_blank'>http://swapen.com/index.php </a><br></td>
						  </tr>
						</table></td>
					  </tr>
					</table>
					";
					$mail = new PHPMailer(); // defaults to using php "mail()"
					$mail->MsgHTML($msg);
					$mail->From       = "mail@swapen.com";
					$mail->FromName   = "Swapen.com";
					$mail->Subject    =": Your friend ".$user_name1." wants you to join Swapen.com";
					$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
					$mail->AddAddress($strEmail, $strEmail);
					$mail->Send();
					
					//echo $msg;
				}	
				else
				{
					$strMessage .="This email id has been already refered : ".$strEmail."<br/>";
				}
			}
			else
			{
				$strMessage .="This email id has been already a registered member : ".$strEmail."<br/>";
			}
		}
	}	
	if(mysql_affected_rows()>0) 
	{	
		$smsg="true";
		$postId=mysql_insert_id();					
	}
	else { $smsg="false"; }	
}

if($_REQUEST['withdraw']=='1')
{	
	header("location:index.php?token_id=2");
}

$sql_comm="SELECT count( * ) TotTrans, sum(refer_comm) AS TotAmt,refer_to_user_id,u.first_name, u.last_name
FROM tbl_refer_comm r
LEFT JOIN tbl_users u ON r.refer_to_user_id = u.user_id
WHERE refer_by_user_id =".$_SESSION['user_id_sess']."
AND isPaid = '0'
GROUP BY refer_to_user_id";

$rst_comm=mysql_query($sql_comm);
//$row_comm=mysql_fetch_array($rst_comm);
$row_comm=getRecordArray($rst_comm);
//print_r($rows);

$sql_comm_user="SELECT  * 
FROM tbl_users u
LEFT JOIN tbl_referer r ON r.refer_to_user_id = u.user_id
WHERE refer_by_user_id =".$_SESSION['user_id_sess']."
AND isActive = '1'";

$rst_comm_user=mysql_query($sql_comm_user);
//$row_comm=mysql_fetch_array($rst_comm);
$row_comm_user=getRecordArray($rst_comm_user);
$user_array=array();

function getRow($set_user_id)
{

	$row=array();
	foreach($row_comm as $temp)
	{
		if($temp->refer_to_user_id==$set_user_id)
		{
			$row=$temp;
		}
	}	
	return $row;
}
if($_REQUEST['ref']=='1')
{	
	$strMessage .="Your withdrawal request has been sent successfully<br/>";
}


?>
<script src="http://www.nileshmahajan.com/swapen/js/jquery-1.4.4.js" type="text/javascript"></script>

<style type="text/css">
	#sell-form { border:0px solid #CCC; vertical-align:top; padding:10px; float:left; width:93%; margin:2%; }

	#sell-form label{
	float: left;
	width: 130px;
	font-weight: bold;
	}
	
	#sell-form input, select, textarea{	
	width: 280px;
	margin-bottom: 5px;
	font-size:12px;
	}
	
	#sell-form textarea{
	height: 250px;
	width: 450px;
	font-size:12px
	}
	
	#sell-form #submitbutton{
	margin-left: 130px;
	margin-top: 5px;
	width: 90px;
	}
	
	#sell-form br{
	clear: left;
	}

	
</style>
<script language="javascript" type="text/javascript">
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// whitespace characters
var whitespace = " \t\n\r";
var sEmail = "Email";
var iEmail = "This field must be a valid email address (user@host.domain). Please reenter it now.";
var pEntryPrompt = "Please enter a ";
var pEmail = "valid email address (like foo@bar.com).";
var defaultEmptyOK = false;
function checkEmail (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (isEmpty(theField.value))) return true;
	else if (!isEmail(theField.value, false)) 
	   return warnInvalid (theField, iEmail);
	else return true;
}
function isEmail (s)
{   if (isEmpty(s)) 
	   if (isEmail.arguments.length == 1) return defaultEmptyOK;
	   else return (isEmail.arguments[1] == true);
   
	// is s whitespace?
	if (isWhitespace(s)) return false;
	
	// there must be >= 1 character before @, so we
	// start looking at character position 1 
	// (i.e. second character)
	var i = 1;
	var sLength = s.length;

	// look for @
	while ((i < sLength) && (s.charAt(i) != "@"))
	{ i++
	}

	if ((i >= sLength) || (s.charAt(i) != "@")) return false;
	else i += 2;

	// look for .
	while ((i < sLength) && (s.charAt(i) != "."))
	{ i++
	}

	// there must be at least one character after the .
	if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
	else return true;
}	
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}
function isWhitespace (s)
{   var i;

    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }   
    return true;
}
function removeSpaces(string) {
 return string.split(' ').join('');
}	

function checkEmails(inputvalue){	
    var pattern=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/;

    if(pattern.test(inputvalue)){         
		return true;   
    }else{   
		return false; 
    }
}

function validateEmail()
{
	var frm=document.frmPost;	
	var strValue=document.frmPost.post_email_address.value;
	var arrEmail=new Array();
	arrEmail=strValue.split("\n");
	var count=arrEmail.length;
	var bReturn=true;
	for(i=0;i<count;i++)
	{
		//alert(removeSpaces(arrEmail[i].toString()));
		if(!checkEmails(arrEmail[i].toString()))
		{
			alert("Please enter valid email : " + arrEmail[i].toString());
			frm.post_email_address.focus();
			bReturn= false;
		}
		//else
//		{
//			alert(arrEmail[i].toString());
//		}
	}	
	return bReturn;
}


</script>
  					
<script>
	function show_popupbox(id)
	{
	 var pos = $('#displaylist'+id).position();
	    var nleft = pos.left;
	    var ntop = pos.top;
	   $('#p'+id).css({'top':ntop,'left':nleft}).show();
	}
</script>
<div id='panel'>

<div class='mypg_left_out'>
<? include("mypg_left.php"); ?>
</div>

<div class='fullbox_out'>

<? include("my_swapen_seller.php"); ?>

<div class="fulldiv" style="margin:10px 0px 0px 0px;">
	
	<p class="pro_ptag">
	<strong class="orangehead" style="margin:0px 0px 0px 7px;">Make Money By Referring People You Know</strong>
	<a href="index.php?amazon_email" style="float:right; margin:0px 10px 0px 0px;">Amazon Payment Account</a>
	</p>
	
	<div class="fulldiv">
		<div class="fullbox_top">&nbsp;</div>
		<div class="fullbox_repeat">

<table width="100%" border="0">

  <tr>
    <td colspan="2">
	
	<table width="100%" align="center"  border="0" cellspacing="0">
      <tr>
	  	<td><?php if($strMessage!="") { echo $strMessage; } ?></td>
	  </tr>
      <tr>
        <td height="100">			
		<form name="frmPost" id="frmPost" method="post" action="" enctype="multipart/form-data">    
			  <input type="hidden" name="keyword" id="keyword">
				<div id="sell-form" style="text-align:center;" align="center">				
					
					<label for="post_description" style="width:100%;">Add Email Addresses (one per line)</label>
					<textarea name="post_email_address" id="post_email_address" class="inputbg" style="margin:10px 0px 0px 0px;"></textarea><br>					
																			
					<input type="submit" onClick="return validateEmail();" id="submitbutton" name="submitbutton" value="Submit"  class="yellow_btn" style=" margin:10px auto 10px auto; float:none;"><br>
				</div><br>
        </form></td>
      </tr>
	  <tr>
		  <td>
		  	<div>
			<table width="660px" border="2" cellspacing="0" style="border-style:solid;" cellpadding="0">
			<tr><td>
			<form id="form1" name="form1" method="post" action="" enctype="multipart/form-data">
			
		  <table width="660px" border="0" cellspacing="0" cellpadding="4">
            <tr>
              <td colspan="2"><strong>Referred Comission</strong> </td>
              <td colspan="2" style="font-size:9px;">The request withdrawal funds for referred Comission are made on the 1st of every month </td>
              </tr>
            <tr>
              <td width="19%">Referred User </td>
              <td width="21%">Total Transactions </td>
              <td width="25%">Total Comission </td>
              <td width="35%" rowspan="2"><img src="images/withdrawl.jpg" id="imgWithDraw" name="imgWithDraw" onclick="document.getElementById('withdraw').value=1;form1.submit();" border="0" height="57" width="298" style="cursor:pointer"  /></td>
            </tr>
			<?php
				$counter=count($row_comm);
				$total=0;
			 for($i=0;$i<$counter;$i++)
			 {
			 //TotTrans, sum( `refer_comm` ) AS TotAmt, `refer_to_user_id` , u.first_name, u.last_name
			 //$total=$total+$row_comm[$i]['TotAmt'];
			 $user_array[]=$row_comm[$i]['refer_to_user_id'];
			 ?>
			<?php /*?><tr>
              <td><?php echo $row_comm[$i]['first_name'].' '.$row_comm[$i]['last_name'];?></td>
              <td align="center" valign="middle"><?php echo $row_comm[$i]['TotTrans'];?></td>
              <td align="center"><?php echo $row_comm[$i]['TotAmt'];?></td>
            </tr><?php */?>			
           <?php 
		   } 
		   $counter_user=count($row_comm_user);
		   //print_r($user_array);
		   for($j=0;$j<$counter_user;$j++)
		   {
			   if (in_array($row_comm_user[$j]['user_id'], $user_array))
			   {
			   	
				$sql_comm_user="SELECT count( * ) TotTrans, sum(refer_comm) AS TotAmt,refer_to_user_id,u.first_name, u.last_name
					FROM tbl_refer_comm r
					LEFT JOIN tbl_users u ON r.refer_to_user_id = u.user_id
					WHERE refer_by_user_id =".$_SESSION['user_id_sess']."
					AND isPaid = '0' AND r.refer_to_user_id=".$row_comm_user[$j]['user_id']." 
					GROUP BY refer_to_user_id";
			   	$rst_comm_user=mysql_query($sql_comm_user);
				$row_User=mysql_fetch_array($rst_comm_user);
				
				$sql_comm_user1="SELECT count( * ) TotTrans, sum(refer_comm) AS TotAmt,refer_to_user_id,u.first_name, u.last_name
					FROM tbl_refer_comm r
					LEFT JOIN tbl_users u ON r.refer_to_user_id = u.user_id
					WHERE refer_by_user_id =".$_SESSION['user_id_sess']."
					AND isPaid = '0' AND r.refer_to_user_id=".$row_comm_user[$j]['user_id']." AND DATEDIFF( CURDATE( ) , buy_date ) <30
					GROUP BY refer_to_user_id";
			   	$rst_comm_user1=mysql_query($sql_comm_user1);
				$row_User1=mysql_fetch_array($rst_comm_user1);
				
				$rem_amt=$row_User['TotAmt'] - $row_User1['TotAmt'];
				
				$total=$total+$rem_amt;
				//echo $row_User['first_name'].' '.$row_User['last_name'];
				
				$sql="select * from tbl_refer_comm r,tbl_users u where refer_by_user_id =".$_SESSION['user_id_sess']." AND isPaid = '0' AND r.refer_to_user_id=".$row_comm_user[$j]['user_id']." AND r.refer_to_user_id = u.user_id";
				$rs=mysql_query($sql) or mysql_error();
				
				?>
				
				<tr>
				  <td><?php echo $row_User['first_name'].' '.$row_User['last_name'];?>
				   
				      <span onclick="show_popupbox('<?=$row_comm_user[$j]['user_id']?>');" id="displaylist<?=$row_comm_user[$j]['user_id']?>" style="cursor:pointer;">+</span>
				      <div style="border: 3px solid rgb(0, 0, 0); position: absolute; width: 300px; top: 100px; left: 100px; display: none; background-color:white; z-index:999; margin:3px;"  id="p<?=$row_comm_user[$j]['user_id']?>">
				       <span style="align:right; color:red;cursor:pointer;" onclick="$('#p<?=$row_comm_user[$j]['user_id']?>').hide();">X</span>
					<div style="float: left; width: 10%; margin-left:5px;" >ID</div>
					<div style="float: left; width: 20%;">Amount</div>
					<div style="float: left; width: 60%;">Time left</div>
					<?
					$i=1;
					while($row=mysql_fetch_array($rs))
					{
						$remainder =0;
						
						//$s=mysql_query("Update tbl_refer_comm set buy_date='2010-12-26' where ref_comm_id='".$row['ref_comm_id']."'");
						
						 $y=date('Y',strtotime($row['buy_date']));
						 $d=date('d',strtotime($row['buy_date']));
						 $m=date('m',strtotime($row['buy_date']));
						
			
			                        $futureTime = mktime(0, 0, 0, date($m), date($d)+30, date($y));
						$d=date('Y-m-d h:i:s',$futureTime);
				                $remainder = getRemainingTime($d);
						?>
						<div style="float: left; width: 10%; margin-left:5px;"><?=$i?></div>
						<div style="float: left; width: 20%;"><?=$row['refer_comm']?></div>
						<div style="float: left; width: 60%;"><?=$remainder?></div>
						<?
						   $i++;
					}
					?>  
				      </div>
				  </td>
				  <td align="center" valign="middle"><?php echo $row_User['TotTrans'];?></td>
				  <td align="center"><?php echo $rem_amt;?></td>
				</tr>
				
				<?php	
			   }
			   else
			   {			   	
			   
		   ?>
		   <tr>
              <td><?php echo $row_comm_user[$j]['first_name'].' '.$row_comm_user[$j]['last_name'];?></td>
              <td align="center" valign="middle">0</td>
              <td align="center">0.00</td>
            </tr>
		   <?php	   
		   		}  
		 }
		   ?>
		   
            <tr>
              <td>&nbsp;</td>
              <td align="center" valign="middle">&nbsp;</td>
              <td align="center" >-------------</td>
              <td>minus amazon transaction fees</td>
            </tr>
			<tr>
              <td>&nbsp;</td>
              <td align="center" valign="middle">&nbsp;</td>
              <td align="center" >$ <?php echo number_format($total,2);?> Total</td>
              <td><input type="hidden"  name="withdraw" id="withdraw" value="<?php echo $withdraw;?>" /></td>
            </tr>
          </table>
		  </form>
		  </td></tr>
			</table>
		</div>	
		  </td>
	  </tr>
    </table></td>
  </tr>
</table>

		</div>
		<div class="fullbox_bot">&nbsp;</div>
	</div>
	
	</div>
	
	
</div>

</div>
<script language="javascript" type="text/javascript">
var varTot=<?php echo $total;?>;
if(varTot=="" || parseInt(varTot)<10)
{
	document.getElementById("imgWithDraw").style.display='none';
	document.getElementById("imgWithDraw").style.visiblity='hidden';
}
</script>